﻿using System.Collections.Generic;
using Plugins.Interfaces;
using Plugins.Threading;

namespace Plugins.Samples.Internal
{
    public interface IWorkItemData
    {
        int Offset { get; }
        int Length { get; }
        string Result { get; }
    }

    class PiWorkItemManager
    {
        private class WorkItemData : IWorkItemData
        {
            public int Offset { get; set; }
            public int Length { get; set; }
            public string Result { get; set; }
        }

        private static List<IWorkItemData> _data = new List<IWorkItemData>();
        public static IEnumerable<IWorkItemData> Data { get { return _data; } }

        private class WorkItem : PluginWorkItem<WorkItemData>
        {
            private int _digits;
            private int _length;
            public WorkItem(int digits, int length) 
            {
                _digits = digits;
                _length = _digits / length;
            }
            protected override int DataCount { get { return _length; } }
            protected override void InitializeData()
            {
                int length = _digits / _length;
                for (int offset = 0; offset < _digits; offset += length)
                {
                    PushData(CreateData(offset, length));
                }
            }
            protected override void ProcessData(WorkItemData data, int threadID)
            {
                data.Result = PiAlgorithm.Calculate(data.Offset, data.Length);
            }
        }

        public static IPluginWorkItem Create(int digits)
        {
            return new WorkItem(digits, 10);
        }

        private static WorkItemData CreateData(int offset, int length)
        {
            WorkItemData result = new WorkItemData()
            {
                Offset = offset,
                Length = length
            };
            _data.Add(result);
            return result;
        }
    }
}
